package team.wuyou.util.HttpSessionUtil;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {

    public static String getRemortIP(HttpServletRequest request) {
        String ipAddress = null;
        // 获取当前请求的 HttpServletRequest
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取 X-Forwarded-For 头部，该头部通常包含客户端真实的 IP 地址
        String xForwardedForHeader = request.getHeader("X-Forwarded-For");

        // 如果 X-Forwarded-For 头部不为空，按照逗号分隔的第一个值为真实 IP 地址
        if (xForwardedForHeader != null && xForwardedForHeader.length() != 0 && !"unknown".equalsIgnoreCase(xForwardedForHeader)) {
            ipAddress = xForwardedForHeader.split(",")[0].trim();
        }

        // 如果 X-Forwarded-For 头部为空或者为 unknown，则尝试获取 RemoteAddr
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        // 如果使用了代理，X-Forwarded-For 可能会包含多个 IP 地址，这时取第一个作为真实 IP
        // 实际生产环境中可能需要根据具体代理的设置进行处理

        return ipAddress;
    }
}

